package catemodel

import (
	"fmt"
	"forum/app/model"
	cateData "forum/app/structData/cate"
	"time"
)

// 定义结构体对应数据库字段
type Cate struct {
	Id          int    `json:"id"`
	Title       string `json:"title"`
	Pid         int    `json:"pid"`
	Sort        int    `json:"sort"`
	Status      int    `json:"status"`
	CreatedTime int64  `json:"created_time"`
	UpdatedTime int64  `json:"updated_time"`
}

func GetList(keyWord string) []Cate {
	db := model.CURD{DB: model.DB}

	//设置默认值
	whereCondition := map[string]interface{}{}

	if keyWord != "" {
		whereCondition = map[string]interface{}{
			"title like": "%" + keyWord + "%",
		}
	}
	fmt.Println(whereCondition)

	list, err := db.Table("cate").
		Fields("id,title,pid,sort,status,created_time,updated_time").
		Where(whereCondition).
		Select()
	if err != nil {
		panic(err)
	}

	var data []Cate

	for list.Next() {
		var cate Cate

		err := list.Scan(&cate.Id,
			&cate.Title,
			&cate.Pid,
			&cate.Sort,
			&cate.Status,
			&cate.CreatedTime,
			&cate.UpdatedTime)

		if err != nil {
			// 处理错误
			continue
		}
		data = append(data, cate)
	}
	return data
}

func Create(params cateData.CreateRequest) int64 {
	db := model.CURD{DB: model.DB}

	data := map[string]interface{}{
		"title":        params.Title,
		"pid":          params.Pid,
		"sort":         params.Sort,
		"status":       params.Status,
		"created_time": time.Now().Unix(),
		"updated_time": time.Now().Unix(),
	}
	id, err := db.Table("cate").Insert(data)
	if err != nil {
		panic(err)
	}
	return id
}
